import { useEffect, useRef, useState } from "react";
import FabricCanvas from "../utils/FabricCanvas";
import { distance, px2cm } from "../utils";

export default function Measure({ isCanvasInitialized }) {
  const canvasRef = useRef(null);
  const imgRef = useRef(null);
  const fabricCanvasRef = useRef(null);
  const [isDrawing, setIsDrawing] = useState(false);
  const [Points, setPoints] = useState([]); //测量点集合

  // 监听 isCanvasInitialized 状态，动态初始化和销毁 FabricCanvas 实例
  useEffect(() => {
    const image = imgRef.current;
    const canvas = canvasRef.current;
    if (image && canvas) {
      // 确保图像加载后设置画布尺寸
      const setCanvasSize = () => {
        const { width, height } = image;
        if (isCanvasInitialized) {
          // 初始化 FabricCanvas 实例
          fabricCanvasRef.current = new FabricCanvas(
            canvasRef.current,
            {
              width,
              height,
            },
            (lines) => {
              const points = lines.map((line) => {
                return px2cm(
                  distance(
                    { x: line.x1, y: line.y1 },
                    { x: line.x2, y: line.y2 }
                  )
                );
              });
              setPoints(points);
            }
          );
        } else {
          // 销毁 FabricCanvas 实例
          if (fabricCanvasRef.current) {
            fabricCanvasRef.current.removeCanvas();
            fabricCanvasRef.current = null;
          }
        }
      };

      if (image.complete) {
        //图像已经被加载
        setCanvasSize();
      } else {
        //等待图像加载完成
        image.onload = setCanvasSize;
      }
    }
    //组件卸载时清理资源
    return () => {
      if (fabricCanvasRef.current) {
        fabricCanvasRef.current.removeCanvas();
        fabricCanvasRef.current = null;
      }
    };
  }, [isCanvasInitialized]);

  //测量
  const toggleDrawing = () => {
    if (isDrawing) {
      fabricCanvasRef.current.finishDrawing();
      setIsDrawing(false);
    } else {
      fabricCanvasRef.current.startDrawing();
      setIsDrawing(true);
    }
  };
  //删除选中的线
  const deleteSelectedLine = () => {
    fabricCanvasRef.current.deleteSelectedLine();
  };
  const nextStep = (dir) => {
    console.log(dir,fabricCanvasRef.current.history.undo);
    if(dir == 'undo'){
      fabricCanvasRef.current.history?.undo();
    }else{
      fabricCanvasRef.current.history?.redo();
    }
  };

  return (
    <div className=" w-full h-full flex relative items-center justify-center">
      <img
        ref={imgRef}
        className=" w-full h-full absolute z-0"
        src="https://diag.cobotsys.com:21001/20240425104921---/Artery-2024-04-25-10-50-39_24b62472-8fb3-4db6-90a3-2df6808ae497/left-2024-04-25-10-50-42/images/auto-L-15-normal-sourceImage-117-_24b62472-8fb3-4db6-90a3-2df6808ae497.jpg"
      ></img>
      <canvas id="canvas" ref={canvasRef}></canvas>
      <div className=" w-30 p-5 absolute right-0 top-50 bg-slate-600 flex items-center justify-center flex-col">
        <button className="btn mb-5" onClick={toggleDrawing}>
          测量
        </button>
        <button className="btn  mb-5" onClick={deleteSelectedLine}>
          删除
        </button>
        <button className="btn mb-5" onClick={() => nextStep("undo")}>
          上一步
        </button>
        <button className="btn" onClick={() => nextStep("redo")}>
          下一步
        </button>
      </div>
      {Points.length > 0 ? (
        <div className=" absolute left-6 right-6 bg-custom-bg w-40 flex flex-col">
          {Points.map((item, index) => {
            return (
              <div key={index} className=" flex items-center justify-around">
                <div className="text-custom-gray">{index + 1}</div>
                <div className="text-custom-gray">{item}cm</div>
              </div>
            );
          })}
        </div>
      ) : null}
    </div>
  );
}
